package com.dycong.common.network;

import com.dycong.common.common.ApplicationConfig;
import lombok.extern.log4j.Log4j;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * Created by dycong on 16-2-29.
 */
@Log4j
public class PooledHttpClient extends SimpleHttpClient{

    public static final int DEFAULT_MAX_TOTAL = 100;
    public static final int DEFAULT_MAX_PER_ROUTE = 10;

    PoolingHttpClientConnectionManager cm;

    private PooledHttpClient(){
        int maxTotal = ApplicationConfig.getInt("maxTotal").orElse(DEFAULT_MAX_TOTAL);
        int maxPerRoute = ApplicationConfig.getInt("maxPerRoute").orElse(DEFAULT_MAX_PER_ROUTE);

        log.info("maxTotal: " + maxTotal + ", maxPerRoute: " + maxPerRoute);

        cm = new PoolingHttpClientConnectionManager();
        // max connections
        cm.setMaxTotal(maxTotal);
        // max connections per route
        cm.setDefaultMaxPerRoute(maxPerRoute);
        // set max connections for a specified route
    }


    static PooledHttpClient instance = new PooledHttpClient();

    public static PooledHttpClient getClient(){
        return instance;
    }

    @Override
    protected HttpClient getHttpClient() {
        return HttpClients.custom()
                .setConnectionManager(cm)
                .build();
    }
}
